package cn.jtool.dig.client.comm.tunnel.protocol;

import cn.jtool.dig.client.comm.MessageExchange;
import cn.jtool.dig.common.model.Commands;
import cn.jtool.dig.common.model.Packet;
import cn.jtool.dig.common.model.PacketBody;
import cn.jtool.dig.common.model.PacketHeader;
import cn.jtool.dig.common.netty.ProtocolProcess;
import cn.jtool.dig.common.netty.SNGenerator;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class P_50_DataTransparent implements ProtocolProcess {

    @Override
    public int protocolId() {
        return Commands.DATA_TRANSPARENT.getCode();
    }

    @Override
    public Packet process(ChannelHandlerContext ctx, Packet packet) {
        boolean sendResult = MessageExchange.toVirtual(packet);
        PacketHeader outheader = new PacketHeader();
        outheader.setCommand(Commands.COMMON_RESPONSE.getCode());
        outheader.setSn(SNGenerator.gen());
        outheader.setDigId(0x00);
        outheader.setChannelId(packet.getHeader().getChannelId());
        PacketBody outbody = new PacketBody();
        outbody.writeByte(this.protocolId());
        outbody.writeWord(packet.getHeader().getSn());
        if(sendResult){
            outbody.writeByte(0x00);
        }else{
            outbody.writeByte(0x01);
        }
        ctx.channel().writeAndFlush(Packet.builder().header(outheader).body(outbody).build());
        return null;
    }
}
